<?php

/**
 * Created by PhpStorm.
 * User:  aLuckyfellow<136171154@qq.com>
 * Date: 2019-04.29
 * Time: 上午13:08
 */

abstract class RedisBasePlugin
{
    const Redis_Host = '127.0.0.1'; //redis 地址

    const Redis_Port = '6379'; //reids 端口

    const Redis_PassWord = null; //reids 密码

    const Redis_Timeout = 0;  //redis 超时时间

    const Redis_DbName = 0;

    private static $redisLink = [];

    private static $RedisRes = [];

    const Redis_Prefix = 'hello_';

    public static function __callStatic($method, $arguments)
    {
        if (empty($arguments)) {
            return null;
        }

        $arguments[0] = self::buildKey($arguments[0]);
        self::$RedisRes['res'] = call_user_func_array([self::getRedisConnect(), $method], $arguments);
        return  self::$RedisRes['res'];
    }

    /**
     * 构造key
     * @param $key
     * @return string
     */
    public static function buildKey($key)
    {
        $redis_prefix = static::Redis_Prefix ? static::Redis_Prefix : self::Redis_Prefix;
        return $redis_prefix . $key;
    }

    public static function set($key, $value, $expire = 0)
    {
        if (empty($key)) {
            return false;
        }

        $key = self::buildKey($key);

        if ($expire !== 0) {
            return self::getRedisConnect()->setex($key, $expire, $value);
        } else {
            return self::getRedisConnect()->set($key, $value);
        }
    }


    private function getRedisConnect()
    {
        $redis_port = static::Redis_Port ? static::Redis_Port : self::Redis_Port;
        $redis_db = static::Redis_DbName ? static::Redis_DbName : self::Redis_DbName;
        self::$redisLink['redis'] = new Redis();
        self::$redisLink['redis']->connect(self::Redis_Host, $redis_port, self::Redis_PassWord);
        self::$redisLink['redis']->auth(self::Redis_Timeout);
        self::$redisLink['redis']->select($redis_db);
        return self::$redisLink['redis'];
    }

    private function __clone()
    {
        return null;
    }
}

